# --- browser_utils/kimi_initialization.py ---
# Kimi初始化相关功能模块

import asyncio
import os
import time
import json
import logging
from typing import Optional, Any, Dict, Tuple

from playwright.async_api import Page as AsyncPage, Browser as AsyncBrowser, BrowserContext as AsyncBrowserContext, Error as PlaywrightAsyncError, expect as expect_async

# 导入配置和模型
from config import *
from models import ClientDisconnectedError
from .kimi_controller import KimiController

logger = logging.getLogger("AIStudioProxyServer")

async def _initialize_kimi_page_logic(browser: AsyncBrowser):
    """初始化Kimi页面逻辑"""
    logger.info("--- 初始化Kimi页面逻辑 ---")
    temp_context: Optional[AsyncBrowserContext] = None
    storage_state_path_to_use: Optional[str] = None
    launch_mode = os.environ.get('LAUNCH_MODE', 'debug')
    logger.info(f"   检测到启动模式: {launch_mode}")
    loop = asyncio.get_running_loop()

    try:
        logger.info("创建新的浏览器上下文...")
        context_options: Dict[str, Any] = {'viewport': {'width': 460, 'height': 800}}
        if storage_state_path_to_use:
            context_options['storage_state'] = storage_state_path_to_use
            logger.info(f"   (使用 storage_state='{os.path.basename(storage_state_path_to_use)}')")
        else:
            logger.info("   (不使用 storage_state)")

        # 代理设置需要从server模块中获取
        import server
        if server.PLAYWRIGHT_PROXY_SETTINGS:
            context_options['proxy'] = server.PLAYWRIGHT_PROXY_SETTINGS
            logger.info(f"   (浏览器上下文将使用代理: {server.PLAYWRIGHT_PROXY_SETTINGS['server']})")
        else:
            logger.info("   (浏览器上下文不使用显式代理配置)")

        context_options['ignore_https_errors'] = True
        logger.info("   (浏览器上下文将忽略 HTTPS 错误)")

        temp_context = await browser.new_context(**context_options)

        found_page: Optional[AsyncPage] = None
        pages = temp_context.pages
        target_url_base = "https://www.kimi.com/"
        target_full_url = "https://www.kimi.com/chat"
        current_url = ""

        for p_iter in pages:
            try:
                page_url_to_check = p_iter.url
                if not p_iter.is_closed() and target_url_base in page_url_to_check:
                    found_page = p_iter
                    current_url = page_url_to_check
                    logger.info(f"   找到已打开的 Kimi 页面: {current_url}")
                    break
            except PlaywrightAsyncError as pw_err_url:
                logger.warning(f"   检查页面 URL 时出现 Playwright 错误: {pw_err_url}")
            except AttributeError as attr_err_url:
                logger.warning(f"   检查页面 URL 时出现属性错误: {attr_err_url}")
            except Exception as e_url_check:
                logger.warning(f"   检查页面 URL 时出现其他未预期错误: {e_url_check} (类型: {type(e_url_check).__name__})")

        if not found_page:
            logger.info(f"-> 未找到合适的现有页面，正在打开新页面并导航到 {target_full_url}...")
            found_page = await temp_context.new_page()
            try:
                await found_page.goto(target_full_url, wait_until="domcontentloaded", timeout=90000)
                current_url = found_page.url
                logger.info(f"-> 新页面导航尝试完成。当前 URL: {current_url}")
            except Exception as new_page_nav_err:
                # 导入save_error_snapshot函数
                from .operations import save_error_snapshot
                await save_error_snapshot("init_new_page_nav_fail")
                error_str = str(new_page_nav_err)
                if "NS_ERROR_NET_INTERRUPT" in error_str:
                    logger.error("\n" + "="*30 + " 网络导航错误提示 " + "="*30)
                    logger.error(f"❌ 导航到 '{target_full_url}' 失败，出现网络中断错误 (NS_ERROR_NET_INTERRUPT)。")
                    logger.error("   这通常表示浏览器在尝试加载页面时连接被意外断开。")
                    logger.error("   可能的原因及排查建议:")
                    logger.error("     1. 网络连接: 请检查你的本地网络连接是否稳定，并尝试在普通浏览器中访问目标网址。")
                    logger.error("     2. Kimi 服务: 确认 https://www.kimi.com/ 服务本身是否可用。")
                    logger.error("     3. 防火墙/代理/VPN: 检查本地防火墙、杀毒软件、代理或 VPN 设置。")
                    logger.error("     4. Camoufox 服务: 确认 launch_camoufox.py 脚本是否正常运行。")
                    logger.error("     5. 系统资源问题: 确保系统有足够的内存和 CPU 资源。")
                    logger.error("="*74 + "\n")
                raise RuntimeError(f"导航新页面失败: {new_page_nav_err}") from new_page_nav_err

        logger.info(f"-> 确认当前位于 Kimi 对话页面: {current_url}")
        await found_page.bring_to_front()

        try:
            # 使用更灵活的方式初始化Kimi控制器
            # 不再严格检查输入框可见性，而是让控制器在实际使用时处理
            kimi_controller = KimiController(found_page, logger, "init")
            
            # 调用控制器的初始化方法，但不强制要求成功
            init_success = await kimi_controller.initialize_page()
            logger.info(f"Kimi控制器初始化结果: {init_success}")
            
            # 即使初始化不完全成功，也继续进行，因为在实际使用时会再次尝试定位元素

            result_page_instance = found_page
            result_page_ready = True

            logger.info(f"✅ Kimi 页面逻辑初始化完成。")
            return result_page_instance, result_page_ready, kimi_controller
        except Exception as input_visible_err:
            from .operations import save_error_snapshot
            await save_error_snapshot("init_fail_input_timeout")
            logger.error(f"Kimi 页面初始化过程中出现错误：{input_visible_err}", exc_info=True)
            # 保存调试信息
            try:
                error_dir = os.path.join(os.path.dirname(__file__), '..', 'errors_py')
                os.makedirs(error_dir, exist_ok=True)
                
                screenshot_path = os.path.join(error_dir, 'kimi_init_error.png')
                await found_page.screenshot(path=screenshot_path, full_page=True)
                logger.info(f"页面截图已保存到: {screenshot_path}")
                
                html_content = await found_page.content()
                html_path = os.path.join(error_dir, 'kimi_init_error.html')
                with open(html_path, 'w', encoding='utf-8') as f:
                    f.write(html_content)
                logger.info(f"页面HTML已保存到: {html_path}")
            except Exception as debug_err:
                logger.warning(f"保存调试信息失败: {debug_err}")
            
            # 即使初始化过程中有错误，也继续进行，因为在实际使用时会再次尝试
            kimi_controller = KimiController(found_page, logger, "init")
            result_page_instance = found_page
            result_page_ready = True
            
            logger.info(f"✅ Kimi 页面逻辑初始化完成（带警告）。")
            return result_page_instance, result_page_ready, kimi_controller
    except Exception as e_init_page:
        logger.critical(f"❌ Kimi 页面逻辑初始化期间发生严重意外错误: {e_init_page}", exc_info=True)
        if temp_context:
            try:
                logger.info(f"   尝试关闭临时的浏览器上下文 due to initialization error.")
                await temp_context.close()
                logger.info("   ✅ 临时浏览器上下文已关闭。")
            except Exception as close_err:
                 logger.warning(f"   ⚠️ 关闭临时浏览器上下文时出错: {close_err}")
        from .operations import save_error_snapshot
        await save_error_snapshot("init_unexpected_error")
        raise RuntimeError(f"Kimi 页面初始化意外错误: {e_init_page}") from e_init_page